--#include "data\config\common\CommonActivityPanelConfig.lua" once			 --通用活动面板的参数
--#include "data\functions\Common\CommonFunc.lua" once				         --一些通用方法
--#include "data\config\item\refreshLib\ItemRefreshLibConfig.lua" once	     --通用物品刷新库

----------------活动相关方法的回调处理---------begin---------------------------
ActivityGetDataDispatcher 		= {}					--客户端请求某活动数据的回调方法
----------------活动相关方法的回调处理---------end---------------------------

-----------------------------------通用活动相关--------begin----------------------------------------------------
--开启后台活动
function OpenBackStageActivity(activityId, sysarg)
	local activitys = {}
	
	local leftTime = System.GetCommonActivityLeftTime(activityId)
	local nPlan = System.GetCommonActivityParam(activityId,0,0,0,0)
	local data = {}
	data.activityId = activityId
	data.leftTime = leftTime
	data.plan = nPlan
	data.day = GetBackStageActivityDayByActivityId(activityId)
	table.insert(activitys, data)
	if sysarg then
		SendOpenCommonActivity(sysarg, activitys )
	else
		local players = LuaHelp.getAllActorList()
		if players then	
			for k, v in ipairs(players) do	
				SendOpenCommonActivity(v, activitys )
			end
		end
	end
end

--关闭后台活动
function CloseBackStageActivity(activityId, sysarg)
	if System.IsCommonActivityOpen(activityId) then
		if sysarg then
			SendCloseCommonActivity(sysarg, activityId )
		else
			local players = LuaHelp.getAllActorList()
			if players then	
				for k, v in ipairs(players) do	
					SendCloseCommonActivity(v, activityId )
				end
			end
		end
	end
end

--根据活动id获取活动时间
function GetBackStageActivityDayByActivityId(actId)
	local ssVar = System.getStaticVar()
	if actId == CommonActivity_DailyRecharge then
		return ssVar.dailyRechargeDay or 1
	end
	return 1
end

--[[
某后台活动、定时活动开启、关闭、跨天时发送
]]
function SendOpenCommonActivity(sysarg, activitys )
	if not activitys or type(activitys) ~= 'table' then
		return
	end
	local npack = DataPack.allocPacket(sysarg, enDefaultEntitySystemID, sSendOpenCommonActivitys)
	if not npack then
		return
	end

	local len = #activitys
	DataPack.writeChar(npack, len)
	for idx = 1, len do
		DataPack.writeShort( npack, activitys[idx].activityId )			--活动ID，服务器与客户端自行约定，不冲突即可
		DataPack.writeUInt(npack, activitys[idx].leftTime)			        --活动剩余时间
		DataPack.writeChar(npack, activitys[idx].plan)			        --活动方案
		DataPack.writeChar(npack, activitys[idx].day or 1)			        --活动状态，0-关闭，1-开启
	end
	
	DataPack.flush(npack)
end

function SendCloseCommonActivity(sysarg, activityId )
	local npack = DataPack.allocPacket(sysarg, enDefaultEntitySystemID, sSendCloseCommonActivity)
	if not npack then
		return
	end

	DataPack.writeShort( npack, activityId )			--活动ID，服务器与客户端自行约定，不冲突即可
		
	DataPack.flush(npack)
end

--[[注册请求某活动的数据的方法
activityId:活动ID，肯定是唯一的，不能重复
]]
ActivityGetDataDispatcher.register = function( activityId, proc )
	--print("----->SceneEnterDispatcher.register, activityId="..activityId)
	if not proc then
		print("ActivityGetDataDispatcher Register, activityId["..activityId.."]，proc is nil")
	end
	ActivityGetDataDispatcher[activityId] = proc
end

--触发请求某活动的数据的方法
ActivityGetDataDispatcher.dispatch = function( sysarg, activityId, funcId )
	--print("----->ActivityGetDataDispatcher.dispatch, activityId="..activityId..", funcId="..funcId)
	local activityGetDataCallProc = ActivityGetDataDispatcher[activityId]
	if activityGetDataCallProc then
		activityGetDataCallProc(sysarg, activityId, funcId)
	end
end



--[[更新每日排行榜和总排行榜数据(暂不使用)
适用于 每日消费+累积消费排行榜；每日充值+累积充值排行榜
activityId 		: 活动ID
dailyRankName	：每日榜
allRankName		：总榜
allRankLimit	: 总榜的达标limit

flag：
	1-本人当日消费
	2-本人当日充值
	3-本人累积消费
	4-本人累积充值
	5-全服当日消费
	6-全服当日充值
	7-全服累积消费
	8-全服累积充值

]]
function UpdateCommonRankDailyAndAll( sysarg, rankType, flag, dailyRankName, allRankName, addValue, allRankLimit )
	local  actorId = Actor.getActorId( sysarg )
	UpdateCommonRankValueById(actorId, dailyRankName, addValue )
	UpdateCommonRankValueById(actorId, allRankName, addValue )

	local name 		= Actor.getName(sysarg)
	local serverId 	= System.getServerId()
	local sex 		= Actor.getIntProperty(sysarg, PROP_ACTOR_SEX)
	local vocation 	= Actor.getIntProperty(sysarg, PROP_ACTOR_VOCATION)
	local circle 	= Actor.getIntProperty(sysarg, PROP_ACTOR_CIRCLE)
	local level 	= Actor.getIntProperty(sysarg, PROP_CREATURE_LEVEL)
	local modelId 	= Actor.getIntProperty(sysarg, PROP_ENTITY_MODELID)				--外形，有时装就是时装外观
	local icon 		= Actor.getIntProperty(sysarg, PROP_ENTITY_ICON)
	local weaponId 	= Actor.getIntProperty(sysarg, PROP_ACTOR_WEAPONAPPEARANCE)		--武器外观
	local SwingId   = Actor.getIntProperty(sysarg, PROP_ACTOR_SWINGAPPEARANCE)		--翅膀外挂

	local newColValues = { name, serverId, sex, vocation, circle, level, modelId, icon, weaponId, SwingId }
	SetCommonRankColumnValueFull(actorId, allRankName, 0, newColValues)	
	SendCommonRankSelfData( sysarg, rankType )

	--AddActivityConsumeLog( sysarg, ActiveIdOnly.ActiveId_NewDouble11,  addValue)
end

--[[
此排行榜包含若干数据，可以根据实际需要存储数据，只要数据与排行榜对应即可
]]
function SetCommonRankColumnValueFull(actorId, rankName, value, newColValues)
	--print("SetCommonRankColumnValueFull, rankName="..rankName..", colIdx="..colIdx..", newColValues="..newColValues)
	local ranking = Ranking.getRanking( rankName )
	if ranking then
		local item = Ranking.getItemPtrFromId( ranking, actorId )
		if item then	--已经榜上有名
			local colNum = Ranking.GetRankColumnCount(ranking)
			for idx=1, #newColValues do
				if idx <= colNum then
					local newColValue = newColValues[idx]
					--print("SetCommonRankColumnValueFull, newColValue="..newColValue)
					Ranking.setSub(item, idx-1, newColValue)
					if Ranking.getSub(item, idx-1) ~= tostring(newColValue) then  --列没有设置成功
						return false
					end
				end
			end
			return true
		else	--新加的
			item = Ranking.addItem(ranking, actorId, value)
			if item then
				local colNum = Ranking.GetRankColumnCount(ranking)
				for idx=1, #newColValues do
					if idx <= colNum then
						local newColValue = newColValues[idx]
						--print("SetCommonRankColumnValueFull, newColValue="..newColValue)
						Ranking.setSub(item, idx-1, newColValue)
						if Ranking.getSub(item, idx-1) ~= tostring(newColValue) then  --列没有设置成功
							return false
						end
					end
				end
			return true
			end
		end
	end
	return false
end

--[[下发本人当日充值、消费元宝数量
注：
	1、这里是记录角色自从开服当日起的每日充值、消费元宝的数量；每天玩家首次跨天（在线跨天或跨天登陆）时清0；
	2、与具体某个活动无关，与其他角色充值、消费无关；不能进行玩家之间的排名；
	3、如果活动或功能不从0点开启、或需要进行排名、或需要与其他玩家进行比较、或需要统一清空，则不要使用此数据，
	而需要另外记录各自活动或功能的充值、消费的排行榜；
]]
function SendCommonDailyChargeAndCounsume( sysarg )
	local pack = DataPack.allocPacket(sysarg, enDefaultEntitySystemID, sSendDailyChargeAndCounsume)
	if (pack ~= nil) then
		local dailyCharge 		= Actor.getDailyChargeYuanBao( sysarg )
		local dailyConsume 		= Actor.getDailyConsumeYuanBao( sysarg )
		local dailyChargeSingle = Actor.getDailyChargeSingleYuanBao( sysarg )
		DataPack.writeUInt(pack, dailyCharge)
		DataPack.writeUInt(pack, dailyConsume)
		DataPack.writeUInt(pack, dailyChargeSingle)
		DataPack.flush(pack)
		--print("SendCommonDailyChargeAndCounsume, dailyCharge="..dailyCharge..", dailyConsume="..dailyConsume..", dailyChargeSingle="..dailyChargeSingle)
	end
end

--------------------------------------------------------------------------------------------------------------------------------


-----------------------------------神秘商店--------begin----------------------------------------------------
--[[
获取某个活动的刷新物品的数据
]]
function CommonSendRefreshItemsData( sysarg, activityId )
	local itemLib, drawNum, drawSame, rankName = GetRefreshItemLibByActivityId( activityId )
	if not CommonRefreshItemFromLib( sysarg, activityId, 0 ) then		--如果自动刷新的条件满足，则自动刷新1次
		return
	end
	DoSendCommonRefreshItems( sysarg, activityId, itemLib.libIdx, drawNum, rankName )
end

--[[
从某个活动的物品库中，刷新物品
activityId，定义在enum enItemRefreshActivityId
byHand:0-自动刷新，1-手动刷新
注意：没有统一的活动ID，需要各自功能自行定义需要的活动ID
1、合服活动
]]
function CommonRefreshItemFromLib( sysarg, activityId, byHand )
	--检查能否进行刷新操作，并扣除消耗
	if not CheckRefreshItemByActivityId( sysarg, activityId, byHand ) then
		local itemLib, drawNum, drawSame, rankName = GetRefreshItemLibByActivityId( activityId )
		DoSendCommonRefreshItems( sysarg, activityId, itemLib.libIdx, drawNum, rankName )
		return false
	end

	--获取抽取库
	local itemLib, drawNum, drawSame, rankName = GetRefreshItemLibByActivityId( activityId )
	if not itemLib then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0058, ttFlyTip)
		return false
	end

	if drawNum <= 0 then
		return false
	end

	--执行抽取
	DoCommonRefreshItemFromLib( sysarg, activityId, itemLib, drawNum, drawSame )
	return true
end

--[[
从某个活动的物品库中，刷新物品
activityId，定义在enum enItemRefreshActivityId
idx:展示在界面上的第N个物品，从1-N
注意：没有统一的活动ID，需要各自功能自行定义需要的活动ID
1、合服活动
]]
function CommonBuyRefreshItem( sysarg, activityId, idx )
	--检查能否进行刷新操作
	if not CheckBuyRefreshItemByActivityId( sysarg, activityId ) then
		local itemLib, drawNum, drawSame, rankName = GetRefreshItemLibByActivityId( activityId )
		DoSendCommonRefreshItems( sysarg, activityId, itemLib.libIdx, drawNum, rankName )
		return
	end

	local itemsVar = GetRefreshItemsSaveVarByActivityId( sysarg, activityId )
	if not itemsVar then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0059, ttFlyTip)
		return
	end

	if not itemsVar[idx] then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0064, ttFlyTip)
		return
	end

	local itemIdx 	= itemsVar[idx][1] or 0
	local buyNum 	= itemsVar[idx][2] or 0
	--print("CommonBuyRefreshItem, itemIdx="..itemIdx..", buyNum="..buyNum)
	if itemIdx <= 0 then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0060, ttFlyTip)
		return
	end

	local itemLib, drawNum, drawSame, rankName = GetRefreshItemLibByActivityId( activityId )
	if not itemLib then			--物品库不存在
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0062, ttFlyTip)
		return
	end

	local item = itemLib.lib[itemIdx]
	if not item then			--物品库不存在
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0061, ttFlyTip)
		return
	end

	local buyNumLimit = item.buyNumLimit
	if not buyNumLimit or buyNumLimit == 0 then
		buyNumLimit = 1 			--缺省限购1次
	end
	if buyNum >= buyNumLimit then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0063, ttFlyTip)
		return
	end

	if not IsBagGridEnough(sysarg, {item}) then
		Actor.sendTipmsg(sysarg, Lang.ScriptTips.COM0015, ttFlyTip)
		return
	end

	local moneyType = item.priceType
	local moneyNum 	= item.price or 0
	if item.discpriceType then				--有折扣价，则按折扣价扣费
		moneyType 	= item.discpriceType
		moneyNum 	= item.discprice or 0
	end
	if moneyNum <= 0 then		--金额错误
		return
	end

	if not CheckConsumeMoney( sysarg, moneyType, moneyNum, 1, false ) then
		return
	end

	if not DoConsumeMoney( sysarg, moneyType, moneyNum, 1, GameLog.clCombineServerBuyShopFee, Lang.ScriptTips.CombineServerLog05, false ) then
		return
	end

	itemsVar[idx][2] = buyNum + 1
	GiveCommonAward(sysarg, {item}, GameLog.clCombineServerBuyShopAdd, Lang.ScriptTips.CombineServerLog06)
	DoSendCommonRefreshItems( sysarg, activityId, itemLib.libIdx, drawNum, rankName )
end

--[[
根据活动ID，判断能否进行刷新操作，并扣除消耗
0-自动刷新，1-手动刷新
]]
function CheckRefreshItemByActivityId( sysarg, activityId, byHand )
	if activityId == enItemRefreshActivity_CombineShop then
		return CheckCombineServerMysticalShop( sysarg, byHand )
	end
	return false
end

--[[
根据活动ID，判断能否进行购买操作
]]
function CheckBuyRefreshItemByActivityId( sysarg, activityId, byHand )
	if activityId == enItemRefreshActivity_CombineShop then
		return CheckCombineServerMysticalShopBuy( sysarg )
	end
	return false
end

--[[
根据活动ID，获得物品抽取库
]]
function GetRefreshItemLibByActivityId( activityId )
	if activityId == enItemRefreshActivity_CombineShop then
		return GetCombineServerMysticalShopLib()
	end
	return nil,0
end

function GetRefreshItemsByActivityId( sysarg, activityId )
	--print("GetRefreshItemsByActivityId, activityId="..activityId)
	if activityId == enItemRefreshActivity_CombineShop then
		return GetCombineServerMysticalShopData( sysarg )
	end
	return nil,nil
end

function GetRefreshItemsSaveVarByActivityId( sysarg, activityId )
	--print("GetRefreshItemsByActivityId, activityId="..activityId)
	if activityId == enItemRefreshActivity_CombineShop then
		return GetCombineServerMysticalShopSaveVar( sysarg )
	end
	return nil
end

function GetRefreshItemsTimeByActivityId( sysarg, activityId )
	--print("GetRefreshItemsByActivityId, activityId="..activityId)
	if activityId == enItemRefreshActivity_CombineShop then
		return GetCombineServerMysticalShopTime( sysarg )
	end
	return nil,nil
end

function SetRefreshItemsTimeByActivityId( sysarg, activityId, refreshTime )
	--print("SetRefreshItemsTimeByActivityId, activityId="..activityId)
	if activityId == enItemRefreshActivity_CombineShop then
		return SetCombineServerMysticalShopTime( sysarg, refreshTime  )
	end
end


--[[
个人神秘商店，做成通用的
]]

--[[
从神秘商店中抽取drawNum个商品
抽取概率，按权重计算
rankName:商店数据源， nil：数据存储在玩家静态变量中
isSame: 是否可以重复抽取
]]
function DoCommonRefreshItemFromLib( sysarg, activityId, itemLib, drawNum, drawSame, rankName )
	--print("DoCommonRefreshItemFromLib, activityId="..activityId..", drawNum="..drawNum)
	--随机抽取N个不同的商品，根据sex、job过滤
	local items = DistributeElemByActor(sysarg, itemLib.lib, drawNum, drawSame)
	DoSaveCommonRefreshItems( sysarg, activityId, items )
	DoSendCommonRefreshItems( sysarg, activityId, itemLib.libIdx, drawNum, rankName )
end

--[[
]]
function DoSaveCommonRefreshItems( sysarg, activityId, items )
	--[[
	if activityId == enItemRefreshActivity_CombineShop then
		SaveCombineServerMysticalShopData( sysarg, items )
	end
	]]
	local itemsVar = GetRefreshItemsSaveVarByActivityId( sysarg, activityId )
	local refreshTime, nextFreshTime = GetRefreshItemsTimeByActivityId( sysarg, activityId )
	local now = System.getCurrMiniTime()
	SetRefreshItemsTimeByActivityId( sysarg, activityId, now )		--更新刷新时间
	for idx, item in ipairs( items ) do
		itemsVar[idx] 		= {}
		itemsVar[idx][1]	= item.itemIdx
		itemsVar[idx][2]	= 0						--本人购买数量为0
		itemsVar[idx][3]	= 0						--全服购买数量为0（保留不使用）
		--print("DoSaveCommonRefreshItems, idx="..idx..", itemIdx="..itemsVar[idx][1])
	end
end

--[[
rankName:商店数据源（暂时不使用）， nil：数据存储在玩家静态变量中
lastFreshTime：距离下一次自动刷新的倒计时
	>=0：是倒计时，面板一直打开，且倒计时为0时，客户端执行一次自动刷新  
	-1：不需要自动刷新，客户端不发出自动刷出消息
	如果面板关闭，则客户端不发出自动刷出消息
]]
function DoSendCommonRefreshItems( sysarg, activityId, libIdx, drawNum, rankName )
	local itemsVar = GetRefreshItemsSaveVarByActivityId( sysarg, activityId )
	local refreshTime, lastFreshTime = GetRefreshItemsTimeByActivityId( sysarg, activityId )
	--local refreshTime, items = GetRefreshItemsByActivityId( sysarg, activityId )
	local npack = DataPack.allocPacket(sysarg, enDefaultEntitySystemID, sSendCommonRefreshItemData)
	if npack  then
		DataPack.writeChar(npack, activityId)
		DataPack.writeChar(npack, libIdx)			--库在RefreshItemLibCfg的下标idx
		DataPack.writeInt(npack, lastFreshTime)	--倒计时，
		DataPack.writeChar(npack, drawNum)
		--print("SendCommonRefreshItems, activityId="..activityId..", libIdx="..libIdx..", refreshTime="..refreshTime..
		--	", lastFreshTime="..lastFreshTime)
		for idx=1, drawNum do
			if not itemsVar[idx] then
				itemsVar[idx] = {}
			end
			--local itemIdx, buyNum, allBuyNum = GetCommonMysticalShopItemData( sysarg, itemIdx, rankName )
			local itemIdx 	= itemsVar[idx][1] or 0
			local buyNum 	= itemsVar[idx][2] or 0 		--本人购买数量
			local allBuyNum = itemsVar[idx][3] or 0 		--全服购买数量（当全服公共刷新时才用）
			
			DataPack.writeChar(npack, idx)
			DataPack.writeShort(npack, itemIdx)
			DataPack.writeChar(npack, buyNum)
			DataPack.writeShort(npack, allBuyNum)
			--print("SendCommonRefreshItems,idx="..idx..",itemIdx="..itemIdx..",buyNum="..buyNum..",allBuyNum="..allBuyNum)
		end
		DataPack.flush(npack)
	end
end


function GetCommonMysticalShopItemData( sysarg, itemIdx, rankName )
	if rankName then
		return GetCommonMysticalShopItemData2( sysarg, itemIdx, rankName )
	else
		return GetCommonMysticalShopItemData1( sysarg, itemIdx )
	end
end

--[[
获取在神秘商店所抽取的第N个商品的数据
数据存储在玩家的静态变量中
]]
function GetCommonMysticalShopItemData1( sysarg, itemIdx )
	local sVar = Actor.getStaticVar( sysarg )
	if not sVar.mysticalShopData then
		sVar.mysticalShopData = {}
	end

	if not sVar.mysticalShopData[itemIdx] then
		sVar.mysticalShopData[itemIdx] = {}
	end
	local itemIdx = sVar.mysticalShopData[itemIdx][1] or 0
	local buyNum = sVar.mysticalShopData[itemIdx][2] or 0
	return itemIdx, buyNum, -1
end

--[[
从排行榜中获取神秘商店的数据
]]
function GetCommonMysticalShopItemData2( sysarg, itemIdx, rankName )
	return 0,0,0
end

-----------------------------------个人神秘商店--------end------------------------------------------------------
